﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Reflection;
using System.IO;
using System.ServiceModel;

namespace CommunitySystem
{
    public partial class XingZhengJieShaoXinWindow : ChildWindow
    {
        private WordActionService.WordActionClient _wordClient = null;
        private int errorCount = 0;
        public XingZhengJieShaoXinWindow(int id)
        {
            InitializeComponent();
            Init();
            if (id > 0)
            {
                _wordClient.GetXingZhengJieshaoXingCompleted += (sender, e) =>
                {
                    var model = e.Result.FirstOrDefault();
                    var letter = CommunitySystem.Model.Silverlight.EntityConvertor.
                        Convert<CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter>(model);
                    _OriginalNO = (int)model.NO;
                    _OriginalYear = (int)model.Year;
                    DataBinding(letter);
                };
                _wordClient.GetXingZhengJieshaoXingAsync("id=" + id);
            }
            else
            {
                CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter letter = new CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter() { CreateDate = DateTime.Now, IsValidate = true };
                DataBinding(letter);
            }
        }
        private int _OriginalNO = 0;
        private int _OriginalYear = 0;
        public XingZhengJieShaoXinWindow(int empid1, int empid2, int empid3, int empid4, int empid5)
        {
            InitializeComponent();
            Init();
            EmpbasicService.EmpBasicServiceClient _empClient = new EmpbasicService.EmpBasicServiceClient();
            CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter letter = null;
            _empClient.GetEmp_BasicInfoCompleted += (sender, e) =>
            {
                letter = new CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter() { CreateDate = DateTime.Now };                
                for (int i=0; i< e.Result.Count; i++)
                {
                    var model = e.Result[i];
                    string idp = "emp" + (i + 1) + "ID";
                    string namep = "emp" + (i + 1) + "Name";
                    string genderp = "emp" + (i + 1) + "Gender";
                    string policialp = "emp" + (i + 1) + "Political";
                    string department = "emp" + (i + 1) + "OrginalDepartment";
                    string Position = "emp" + (i + 1) + "OriginalPosition";
                    string level = "emp" + (i + 1) + "Level";
                    PropertyInfo pi = letter.GetType().GetProperty(idp);
                    pi.SetValue(letter, model.ID, null);
                    pi = letter.GetType().GetProperty(namep);
                    pi.SetValue(letter, model.Name, null);
                    pi = letter.GetType().GetProperty(genderp);
                    pi.SetValue(letter, model.Gender, null);
                    pi = letter.GetType().GetProperty(policialp);
                    pi.SetValue(letter, model.Political, null);
                    pi = letter.GetType().GetProperty(department);
                    pi.SetValue(letter, model.OrgName, null);
                    pi = letter.GetType().GetProperty(Position);
                    pi.SetValue(letter, model.PositionName, null);
                    pi = letter.GetType().GetProperty(level);
                    pi.SetValue(letter, model.DutyLevel, null);
                }
                DataBinding(letter);
            };
            if (empid1 != 0 || empid2 != 0 || empid3 != 0 || empid4 != 0 || empid5 != 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("("); 
                sb.Append(empid1);
                sb.Append(" , ");
                sb.Append(empid2);
                sb.Append(" , ");
                sb.Append(empid3);
                sb.Append(" , ");
                sb.Append(empid4);
                sb.Append(" , ");
                sb.Append(empid5);
                sb.Append(")");
                _empClient.GetEmp_BasicInfoAsync("", sb.ToString(), "", "", 0, 20, "", "",true,true);
            }
            else
            {
                letter = new CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter() { CreateDate = DateTime.Now };
                DataBinding(letter);
            }

        }

        private void Init()
        {
            this.BindingValidationError += (sender, e) =>
            {
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    errorCount++;
                }
                else if (e.Action == ValidationErrorEventAction.Removed)
                {
                    errorCount--;
                }
            };
            _wordClient = new WordActionService.WordActionClient();

            _wordClient.GetNOAcoordingToYearCompleted += (sender1, e1) =>
            {
                //根据年获得概念的最大字号
                if ((this.DataContext as CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter).NO == null)//初始复职
                {
                    (this.DataContext as CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter).NO = (1 + e1.Result);
                }
                else
                {
                    var letter = e1.UserState as WordActionService.Word_XingZhengJieShaoLetter;

                    if ((int)(this.DataContext as CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter).NO <= e1.Result)//保存时验证
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("文号必须大于" + e1.Result);
                    }
                    else
                    {
                        if (letter != null)
                        {
                            _wordClient.InsertWord_XingZhengJieShaoLetterAsync(letter);
                        }
                    }
                }
            };

            _wordClient.InsertWord_XingZhengJieShaoLetterCompleted += (sender1, e1) =>
            {
                //保存结果
                if (e1.Error == null)
                {
                    if (!string.IsNullOrEmpty(e1.Result))
                    {
                        try
                        {
                            string serverpath = _wordClient.InnerChannel.Via.AbsoluteUri.Replace(_wordClient.InnerChannel.Via.AbsolutePath, "");
                            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(serverpath + e1.Result, UriKind.RelativeOrAbsolute));
                        }
                        catch (Exception ex)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage("导出失败,可能原因:\n" + ex.Message);
                            return;
                        }
                    }
                    else
                    {
                        SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                    }
                    this.DialogResult = true;
                }
                else
                {                   
                   SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败,可能原因:\n" + e1.Error);
                }
            };
        }

        private void DataBinding(CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter letter)
        {
            if (letter.ID > 0)
            {
               // CancelButton.Visibility = System.Windows.Visibility.Collapsed;
                if (letter.Status.Equals("撤销"))
                {
                    RevertButton.Visibility = System.Windows.Visibility.Collapsed;
                    CancelButton.Visibility = System.Windows.Visibility.Collapsed;
                }
                else if (letter.Status.Equals("暂存"))
                {
                    RevertButton.Visibility = System.Windows.Visibility.Collapsed;
                    CancelButton.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    OKButton.Visibility = System.Windows.Visibility.Collapsed;
                    CancelButton.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            else
            {
                RevertButton.Visibility = System.Windows.Visibility.Collapsed;
            }
            this.DataContext = letter;
            if (letter.ID <= 0 || letter.ID == null)
            {
                _wordClient.GetNOAcoordingToYearAsync((int)letter.Year);
            }
        }

        private CommunitySystem.WordActionService.Word_XingZhengJieShaoLetter GetData()
        {
            var letter = this.DataContext as CommunitySystemModel.Model.Silverlight.Word_XingZhengJieShaoLetter;
            return CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                        <CommunitySystem.WordActionService.Word_XingZhengJieShaoLetter>(letter);
        }

        private void SaveData(CommunitySystem.WordActionService.Word_XingZhengJieShaoLetter letter)
        {
            #region 验证绑定数据
            System.Windows.Data.BindingExpression beUsername = null;
            foreach (var ui in LayoutRoot.Children)
            {
                beUsername = null;
                if (ui is TextBox)
                {
                    beUsername = (ui as TextBox).GetBindingExpression(TextBox.TextProperty);
                }
                else if (ui is DatePicker)
                {
                    beUsername = (ui as DatePicker).GetBindingExpression(DatePicker.SelectedDateProperty);
                }
                if (beUsername != null)
                {
                    beUsername.UpdateSource();
                }                
            }
            if(errorCount >0)
            {
                return;
            }
            #endregion

            #region 人员数据验证
            if (string.IsNullOrEmpty(letter.emp1Name) &&
                string.IsNullOrEmpty(letter.emp2Name) &&
                string.IsNullOrEmpty(letter.emp3Name) &&
                string.IsNullOrEmpty(letter.emp4Name) &&
                string.IsNullOrEmpty(letter.emp5Name))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请至少填写一个人员信息");
                return;
            }
            else
            {
                if (!string.IsNullOrEmpty(letter.emp1Name))//第一个不为空
                {
                    if (string.IsNullOrEmpty(letter.emp1Gender))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp1Name + "的性别不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp1Political))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp1Name + "的政治面貌不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp1OrginalDepartment))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp1Name + "的原工作部门不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp1OriginalPosition))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp1Name + "的原职位不能为空!");
                        return;
                    }
                }
                if (!string.IsNullOrEmpty(letter.emp2Name))//第2个不为空
                {
                    if (string.IsNullOrEmpty(letter.emp2Gender))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp2Name + "的性别不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp2Political))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp2Name + "的政治面貌不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp2OrginalDepartment))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp2Name + "的原工作部门不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp2OriginalPosition))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp2Name + "的原职位不能为空!");
                        return;
                    }
                }
                if (!string.IsNullOrEmpty(letter.emp3Name))//第3个不为空
                {
                    if (string.IsNullOrEmpty(letter.emp3Gender))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp3Name + "的性别不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp3Political))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp3Name + "的政治面貌不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp3OrginalDepartment))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp3Name + "的原工作部门不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp3OriginalPosition))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp3Name + "的原职位不能为空!");
                        return;
                    }
                }
                if (!string.IsNullOrEmpty(letter.emp4Name))//第4个不为空
                {
                    if (string.IsNullOrEmpty(letter.emp4Gender))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp4Name + "的性别不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp4Political))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp4Name + "的政治面貌不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp4OrginalDepartment))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp4Name + "的原工作部门不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp4OriginalPosition))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp4Name + "的原职位不能为空!");
                        return;
                    }
                }
                if (!string.IsNullOrEmpty(letter.emp5Name))//第5个不为空
                {
                    if (string.IsNullOrEmpty(letter.emp5Gender))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp5Name + "的性别不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp5Political))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp5Name + "的政治面貌不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp5OrginalDepartment))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp5Name + "的原工作部门不能为空!");
                        return;
                    }
                    if (string.IsNullOrEmpty(letter.emp5OriginalPosition))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(letter.emp5Name + "的原职位不能为空!");
                        return;
                    }
                }
            }
            #endregion

            if (letter.ID > 0 && letter.Year == _OriginalYear && letter.NO == _OriginalNO)//如果未编辑文号则不需验证文号
            {
                _wordClient.InsertWord_XingZhengJieShaoLetterAsync(letter);
            }
            else
            {
                
                _wordClient.GetNOAcoordingToYearAsync((int)letter.Year, letter);     //验证文号;       
            }
        }
        private SaveFileDialog sf = null;
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            var letter = GetData();
            sf = null;
            letter.Status = "开出";
            //var saveFile = new SaveFileDialog() { Filter = "office 2003| *.xls" };
            //if (saveFile.ShowDialog() == true)
            //{
            //    sf = saveFile;
            //}
            SaveData(letter);
           
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            var letter = GetData();
            letter.Status = "暂存";
            SaveData(letter);
        }

        private void PreButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void RevertButton_Click(object sender, RoutedEventArgs e)
        {
            var letter = GetData();
            letter.Status = "撤销";
            SaveData(letter);
        }
    }
}

